<route lang="json">
{
    "name": "bannerManage",
    "meta": {
        "title": "控制台-轮播图管理",
        "requiresAuth": true
    }
}
</route>

<script setup lang="ts">
import type { UploadRequestOptions } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'
import { addBanner, delBanner, getBannerList, updateBannerFlag } from '~/api/banner'
import { uploadImage } from '~/api/file'

// 定义轮播图接口类型
interface Banner {
  bannerid: string // 后端返回的是 bannerid 而不是 id
  img: string // 后端返回的是 img 而不是 imageUrl
  alt: string // 后端返回的是 alt 而不是 title
  link?: string
  flag?: boolean // 后端返回的是 flag 而不是 status
  [key: string]: any
}

// 轮播图列表数据
const bannerList = ref<Banner[]>([])
const loading = ref(false)

// 表格分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
})

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('添加轮播图')
const formLoading = ref(false)

// 表单数据
const formData = reactive({
  id: '',
  title: '',
  imageUrl: '',
  link: '',
  sort: 0,
  status: 1,
})

// 表单规则
const rules = {
  title: [{ required: true, message: '请输入轮播图标题', trigger: 'blur' }],
  imageUrl: [{ required: true, message: '请上传轮播图图片', trigger: 'change' }],
}

const formRef = ref()

// 获取轮播图列表
async function fetchBannerList() {
  loading.value = true
  try {
    const res = await getBannerList()
    if (res && Array.isArray(res)) {
      bannerList.value = res
      pagination.total = res.length
    }
    else if (res && typeof res === 'object' && Array.isArray(res.data)) {
      bannerList.value = res.data
      pagination.total = res.data.length
    }
    else if (res && typeof res === 'object' && res.data === null) {
      // 处理 { data: null } 的情况
      bannerList.value = []
      pagination.total = 0
    }
    else {
      bannerList.value = []
      pagination.total = 0
    }

    // 打印获取到的数据，便于调试
    console.warn('获取到的轮播图数据:', bannerList.value)
  }
  catch (error) {
    console.error('获取轮播图列表失败:', error)
    ElMessage.error('获取轮播图列表失败')
    bannerList.value = []
    pagination.total = 0
  }
  finally {
    loading.value = false
  }
}

// 处理分页变化
function handleCurrentChange(val: number) {
  pagination.currentPage = val
}

function handleSizeChange(val: number) {
  pagination.pageSize = val
  pagination.currentPage = 1
}

// 计算当前页的数据
const currentPageData = computed(() => {
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return bannerList.value.slice(start, end)
})

// 打开添加对话框
function openAddDialog() {
  dialogTitle.value = '添加轮播图'
  Object.assign(formData, {
    id: '',
    title: '',
    imageUrl: '',
    link: '',
    sort: 0,
    status: 1,
  })
  dialogVisible.value = true
}

// 打开编辑对话框
function openEditDialog(row: Banner) {
  dialogTitle.value = '编辑轮播图'
  Object.assign(formData, {
    id: row.bannerid,
    title: row.alt,
    imageUrl: row.img,
    link: row.link || '',
    sort: row.sort || 0,
    status: row.flag === true ? 1 : 0,
  })
  dialogVisible.value = true
}

// 提交表单
async function submitForm() {
  if (!formRef.value)
    return

  await formRef.value.validate(async (valid: boolean) => {
    if (!valid)
      return

    formLoading.value = true
    try {
      if (formData.id) {
        // 编辑
        await updateBannerFlag({
          bannerid: formData.id,
          flag: formData.status === 1 ? '1' : '0', // 将布尔值转换为字符串
        })
        ElMessage.success('更新轮播图成功')
      }
      else {
        // 添加
        await addBanner({
          img: formData.imageUrl,
          alt: formData.title,
          link: formData.link || '',
        })
        ElMessage.success('添加轮播图成功')
      }
      dialogVisible.value = false
      fetchBannerList()
    }
    catch (error) {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
    finally {
      formLoading.value = false
    }
  })
}

// 删除轮播图
function handleDelete(row: Banner) {
  ElMessageBox.confirm('确定要删除该轮播图吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await delBanner(row.bannerid)
      ElMessage.success('删除成功')
      fetchBannerList()
    }
    catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 创建FormData的辅助函数
function createFormData(): FormData {
  return new FormData()
}

// 创建Promise.reject的辅助函数
function rejectPromise(err: any): Promise<never> {
  return Promise.reject(err)
}

// 上传图片成功回调
function handleUploadSuccess(res: any) {
  // 获取上传后的文件URL
  const fileUrl = res.fileUrl || res.data?.fileUrl || ''
  if (fileUrl) {
    // 拼接完整URL
    formData.imageUrl = `http://47.94.6.186:3001${fileUrl}`
    // 自动填充链接字段
    formData.link = formData.imageUrl
  }
  else {
    formData.imageUrl = res.url || res.data?.url || ''
  }
}

// 页面加载时获取轮播图列表
onMounted(() => {
  fetchBannerList()
})
</script>

<template>
  <div class="banner-manage-container">
    <div class="banner-header">
      <h2 class="banner-title">
        轮播图管理
      </h2>
      <el-button type="primary" @click="openAddDialog">
        添加轮播图
      </el-button>
    </div>

    <!-- 轮播图列表 -->
    <el-card shadow="hover" class="banner-card">
      <el-table v-loading="loading" :data="currentPageData" stripe border style="width: 100%">
        <!-- 序号列 -->
        <el-table-column type="index" label="序号" width="60" />

        <!-- 标题列 -->
        <el-table-column prop="alt" label="标题" min-width="120" show-overflow-tooltip />

        <!-- 图片列 -->
        <el-table-column label="图片" width="180">
          <template #default="scope">
            <el-image
              v-if="scope.row.img" :src="scope.row.img"
              preview-teleported
              :preview-src-list="[scope.row.img]"
              fit="cover"
              style="width: 150px; height: 80px"
            />
            <div v-else class="no-image">
              无图片
            </div>
          </template>
        </el-table-column>

        <!-- 链接列 -->
        <el-table-column prop="link" label="链接" min-width="180" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.link || '-' }}
          </template>
        </el-table-column>

        <!-- 排序列 -->
        <el-table-column prop="sort" label="排序" width="80" />

        <!-- 状态列 -->
        <el-table-column prop="flag" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.flag === true ? 'success' : 'info'">
              {{ scope.row.flag === true ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 创建时间列 -->
        <el-table-column prop="createTime" label="创建时间" min-width="180">
          <template #default="scope">
            {{ scope.row.createTime || '-' }}
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="openEditDialog(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" destroy-on-close>
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入轮播图标题" />
        </el-form-item>
        <el-form-item label="图片" prop="imageUrl">
          <el-upload
            class="banner-upload" action="/admin/file/upload" :show-file-list="false"
            :on-success="handleUploadSuccess" :http-request="(options: UploadRequestOptions) => {
              const formData = createFormData()
              formData.append('img', options.file)
              return uploadImage(formData).then(res => {
                options.onSuccess(res)
              }).catch(err => {
                options.onError(err)
                return rejectPromise(err)
              })
            }"
          >
            <el-image v-if="formData.imageUrl" :src="formData.imageUrl" fit="cover" class="upload-image" />
            <el-icon v-else class="upload-icon">
              <Plus />
            </el-icon>
          </el-upload>
          <div class="upload-tip">
            建议尺寸: 1920 x 500 像素
          </div>
        </el-form-item>
        <el-form-item label="链接" prop="link">
          <el-input v-model="formData.link" placeholder="图片链接将自动填充" disabled />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">
              启用
            </el-radio>
            <el-radio :label="0">
              禁用
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="formLoading" @click="submitForm">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.banner-manage-container {
  padding: 20px;

  .banner-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .banner-title {
      font-size: 20px;
      font-weight: 600;
      margin: 0;
    }
  }

  .banner-card {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .no-image {
    width: 150px;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
    color: #909399;
    border: 1px dashed #d9d9d9;
  }

  .banner-upload {
    .upload-image {
      width: 200px;
      height: 100px;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }

    .upload-icon {
      font-size: 28px;
      color: #8c939d;
      width: 200px;
      height: 100px;
      line-height: 100px;
      text-align: center;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
    }

    .upload-tip {
      font-size: 12px;
      color: #909399;
      margin-top: 5px;
    }
  }
}
</style>
